package com.smartappsnetwork.personalexpenses.database;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.preference.PreferenceManager;


public class DatabaseHelper extends SQLiteOpenHelper 
{
	public final static String DB_NAME = "PersonalExpences.sqlite";
	private final static String DB_KEY = "db_key";
	
	public static String DATABASE_PATH;
	private static SQLiteDatabase sqliteDatabase; 
	private static int DB_VERSION = 1;
	
    private static Context myContext;
    private SharedPreferences sharedPreference;
    private SharedPreferences.Editor editor;
    
	
	public DatabaseHelper(Context context) 
    {	 
    	super(context, DB_NAME, null, DB_VERSION = getVersionCode(myContext = context));
        DATABASE_PATH = context.getFilesDir().toString() + "/" + DB_NAME;
        sharedPreference = PreferenceManager.getDefaultSharedPreferences(myContext);
        initDB();
    }

	private void initDB()
	{
		if(isDbExists())
		{
			if(getVersion() != DB_VERSION)
			{
				myContext.deleteDatabase(DATABASE_PATH);
		        copyDataBase();
			}
			else
			{
				openDataBase();
			}
		}
		else
		{
	       copyDataBase();
		}
		
	}
	
	
	 /** Get the database version from a shared preference*/
	private int getVersion()
	{
		return sharedPreference.getInt(DB_KEY, 1);
	}
	
	
    /** Save the database version in a shared preference*/
	private void saveVersion()
    {
		editor= sharedPreference.edit();
    	editor.putInt(DB_KEY, DB_VERSION);
    	editor.commit();
    }

    
    private boolean isDbExists()
    {
        return new File(DATABASE_PATH).exists();
    }
    
    
  //To open the database
    public static SQLiteDatabase openDataBase() throws SQLException
    {	 
    	//Open the database
    	if(sqliteDatabase == null || !sqliteDatabase.isOpen())    
    		sqliteDatabase = SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);
    	
    	return sqliteDatabase;
    }
    
    
    public synchronized static void closedatabase() 
    { 
	    if(sqliteDatabase != null)
		    sqliteDatabase.close(); 
	}

	@Override
	public void onCreate(SQLiteDatabase db)
	{
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
	{
		
	}
	
	public static int getVersionCode(Context context)
	{
	    int version = -1;
	    try 
	    {
	        PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA);
	        version = pInfo.versionCode;
	    }
	    catch (NameNotFoundException e1)
	    {
	    }
	    return version;
	}
	
	public synchronized static DictionaryEntry[][] get(String query_str)
	{
		
		DictionaryEntry dir = null;
		String[] columns;
		int index;
		int rowIndex = 0;
		DictionaryEntry[] row_obj = null; //An array of columns and their values
		DictionaryEntry[][] data_arr = null;
		Cursor c;	
		
		if(sqliteDatabase != null)
		{
			try 
			{
				openDataBase();
				c = sqliteDatabase.rawQuery(query_str, null);
				if(c.moveToFirst())
				{
					rowIndex = 0;
					data_arr = new DictionaryEntry[c.getCount()][];
					do
					{
						columns = c.getColumnNames();
						row_obj = new DictionaryEntry[columns.length];
						for(int i=0; i<columns.length; i++)
						{
							dir = new DictionaryEntry(); 							
							dir.key = columns[i];
							index = c.getColumnIndex(dir.key);
							dir.value = c.getString(index);
							row_obj[i] = dir;
						}
						data_arr[rowIndex] = row_obj;
						rowIndex++;
					}
					while(c.moveToNext());
				}
				c.close();
			}
			catch(Exception e) 
			{
				e.printStackTrace();
			}
		}
		return data_arr;
	}
	
	public void copyDataBase()
    {
		//If database not copied from assets
		try
		{
			boolean isFound = false;
        	int i=0;
        	String str = "";
        	ZipFile zip = null;
        	ZipEntry zipen = null;
        	while(!isFound)
        	{
        		try
        		{
        			if(i == 0)
        			{
        				str = "";
        			}
        			else
        			{
        				str = "-"+i;
        			}
        			zip = new ZipFile("/data/app/"+myContext.getPackageName()+str+".apk");
        			zipen = zip.getEntry("assets/" + DB_NAME);
        			isFound = true;
        		}
                catch(Exception e)
                {
                	isFound = false;
                }
                ++i;
        	}
        	
            InputStream is = zip.getInputStream(zipen);
            OutputStream os = null;
            
            os = myContext.openFileOutput(DB_NAME, Context.MODE_WORLD_READABLE);
            
            int len;
            byte[] buffer = new byte[4096];
            while ((len = is.read(buffer)) >= 0)
            {
                os.write(buffer, 0, len);
            }
            is.close();
            os.close();
              
            openDataBase();
        }
        catch (Exception e) 
        {
        	e.printStackTrace();
        }
		finally
		{
			saveVersion();
		}
    }
}
